import opencascade from "replicad-opencascadejs/src/replicad_single.js";
import opencascadeWasm from "replicad-opencascadejs/src/replicad_single.wasm?url";
import { setOC } from "replicad";
import { expose } from "comlink";

// We import our model as a simple function
import { drawBox,drawElipse } from "./cad";

// This is the logic to load the web assembly code into replicad
let loaded = false;
const init = async () => {
  if (loaded) return Promise.resolve(true);

  const OC = await opencascade({
    locateFile: () => opencascadeWasm,
  });

  loaded = true;
  setOC(OC);

  return true;
};
const started = init();

function createBlob(thickness) {
  // note that you might want to do some caching for more complex models
  return started.then(() => {
    return drawBox(thickness).blobSTL();
  });
}

function createMesh(thickness) {
  return started.then(() => {
    const bar = drawElipse(thickness);
    // This is how you get the data structure that the replica-three-helper
    // can synchronise with three BufferGeometry
    console.time("get mesh");
    const faces = bar.mesh({tolerance:0.1,angularTolerance:0.1});
    const edges = bar.meshEdges();
    console.timeEnd("get mesh");
    return {
      faces: faces,
      edges: edges,
    };
  });
}

// comlink is great to expose your functions within the worker as a simple API
// to your app.
expose({ createBlob, createMesh });